package com.bmf.module.rbac.service.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bmf.core.result.PageResponse;
import com.bmf.module.rbac.entity.Organization;
import com.bmf.module.rbac.entity.RbacUser;
import com.bmf.module.rbac.mapper.OrganizationMapper;
import com.bmf.module.rbac.service.OrganizationService;
import com.bmf.module.rbac.service.RbacUserService;
import com.bmf.module.rbac.vo.OrganizationCreateVo;
import com.bmf.module.rbac.vo.OrganizationResultVo;
import com.bmf.module.rbac.vo.OrganizationUpdateVo;
import com.bmf.utils.BeanCopyUtils;
import com.bmf.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * (Organization)表服务实现类
 *
 * @author makejava
 * @since 2023-01-06 17:01:18
 */
@Service("organizationService")
public class OrganizationServiceImpl extends ServiceImpl<OrganizationMapper, Organization> implements OrganizationService {

    @Autowired
    private RbacUserService rbacUserService;

    @Autowired
    private OrganizationService organizationService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer insert(OrganizationCreateVo organizationCreateVo) {
        Organization organization = BeanCopyUtils.copyBean(organizationCreateVo, Organization.class);
        save(organization);
        if(organization.getRootId()==null){
            organization.setRootId(organization.getId());
            updateById(organization);
        }
        return organization.getId();
    }

    @Override
    public List<OrganizationResultVo> selectAll() {
        LambdaQueryWrapper<Organization> wrapper = new LambdaQueryWrapper<>();
        //1.判断角色
        //1.1总管理员能查询所有 1.2管理员能查询根节点下所有
        if(SecurityUtils.getUserId()!=1){
            if(SecurityUtils.getLoginUser().getUser().getOrganizationId()!=null){
                List<Integer> list = this.getIdsByRootId(SecurityUtils.getLoginUser().getUser().getOrganizationId());
                if(CollUtil.isEmpty(list)){
                    return null;
                }
                wrapper.in(Organization::getId, list);
            }
        }
        List<Organization> list = list(wrapper);
        if(CollUtil.isNotEmpty(list)){
            List<OrganizationResultVo> organizationResultVos = BeanCopyUtils.copyBeanList(list, OrganizationResultVo.class);
            return organizationResultVos.stream().filter(s -> s.getParentId() == 0).peek(s -> setChildren(organizationResultVos, s)).collect(Collectors.toList());
        }
        return null;
    }
    private void setChildren(List<OrganizationResultVo> organizationResultVos,OrganizationResultVo organizationResultVo){
        List<OrganizationResultVo> childrens = organizationResultVos.stream().filter(s -> s.getParentId().equals(organizationResultVo.getId())).peek(s -> setChildren(organizationResultVos, s))
                .collect(Collectors.toList());
        organizationResultVo.setChildrens(childrens);
    }

    @Override
    public void delete(List<Integer> ids) {
        removeByIds(ids);
    }

    @Override
    public void update(OrganizationUpdateVo organizationUpdateVo) {
        updateById(BeanCopyUtils.copyBean(organizationUpdateVo, Organization.class));
    }

    @Override
    public OrganizationResultVo selectOne(Serializable id) {
        Organization byId = getById(id);
        if(byId==null){
            return null;
        }
        return BeanCopyUtils.copyBean(byId,OrganizationResultVo.class);
    }

    @Override
    public List<Integer> getAllParentOrganizationIds(Integer organizationId) {
        List<Integer> ids = new ArrayList<>();
        Organization byId = getById(organizationId);
        if(ObjectUtil.isEmpty(byId)){
            return null;
        }
        if(byId.getParentId()==0){
            ids.add(organizationId);
            return ids;
        }
        LambdaQueryWrapper<Organization> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Organization::getRootId, byId.getRootId());
        List<Organization> list = list(wrapper);
        if(CollUtil.isNotEmpty(list)){
            Map<Integer, Integer> map = list.stream().collect(Collectors.toMap(Organization::getId, Organization::getParentId));
            Integer id = byId.getId();
            ids.add(id);
            Integer parentId = byId.getParentId();
            while (true){
                if(parentId==0){
                    break;
                }
                ids.add(parentId);
                parentId = map.get(parentId);
            }
            return ids;
        }
        return null;
    }

    @Override
    public List<OrganizationResultVo> selectByOrganizationId(Integer id) {
        LambdaQueryWrapper<Organization> wrapper = new LambdaQueryWrapper<>();
        if(SecurityUtils.getLoginUser().getUser().getOrganizationId()!=null){
            List<Integer> list = this.getIdsByRootId(SecurityUtils.getLoginUser().getUser().getOrganizationId());
            if(CollUtil.isEmpty(list)){
                return null;
            }
            wrapper.in(Organization::getId, list);
        }
        if(id==null){
            //查找根节点
            wrapper.eq(Organization::getParentId, 0);
            List<Organization> list = list(wrapper);
            if(CollUtil.isNotEmpty(list)){
                return list.stream().map(s->BeanCopyUtils.copyBean(s, OrganizationResultVo.class)).peek(s->s.setDisabled(true)).collect(Collectors.toList());
            }
        }
        //查找子节点和子节点成员
        wrapper.eq(Organization::getParentId, id);
        List<Organization> list = list(wrapper);
        List<OrganizationResultVo> organizationResultVos = new ArrayList<>();
        if(CollUtil.isNotEmpty(list)){
            organizationResultVos = list.stream().map(s -> BeanCopyUtils.copyBean(s, OrganizationResultVo.class)).peek(s -> s.setDisabled(true)).collect(Collectors.toList());
        }
        //查询人员
        List<RbacUser> list1 = rbacUserService.selectByOrganizationId(id);
        if(CollUtil.isNotEmpty(list1)){
            List<OrganizationResultVo> collect = list1.stream().map(s -> new OrganizationResultVo(s.getId(), s.getName(), null,null, false,true,null)).collect(Collectors.toList());
            organizationResultVos.addAll(collect);
        }
        return organizationResultVos;
    }

    @Override
    public List<Integer> getIdsByRootId(Integer organizationId) {
        Organization byId = getById(organizationId);
        if(byId==null){
            return null;
        }
        LambdaQueryWrapper<Organization> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(Organization::getId).in(Organization::getRootId, byId.getRootId());
        List<Organization> list = list(wrapper);
        if(CollUtil.isEmpty(list)){
            return new ArrayList<>();
        }
        return list.stream().map(Organization::getId).collect(Collectors.toList());
    }
}
